package com.pm.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pm.common.OAService;
import com.pm.common.config.ParamConfig;
import com.pm.common.core.domain.AjaxResult;
import com.pm.common.core.domain.entity.ProjectListNodeMember;
import com.pm.common.core.domain.model.LoginUser;
import com.pm.common.enums.TaskStatusEnum;
import com.pm.common.utils.PlmSoapUtil;
import com.pm.common.utils.SecurityUtils;
import com.pm.project.domain.vo.ProjectListNodeMemberVO;
import com.pm.project.domain.vo.ProjectListVO;
import com.pm.project.domain.vo.ProjectTempleteDefineVO;
import com.pm.project.mapper.ProjectListNodeMapper;
import com.pm.project.mapper.ProjectListNodeMemberMapper;
import com.pm.project.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.net.ssl.*;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<ProjectListNodeMemberMapper,ProjectListNodeMember> implements TaskService {

    @Resource
    ProjectListNodeMapper projectListNodeMapper;

    @Resource
    ParamConfig paramConfig;

    @Resource
    ProjectListNodeMemberMapper projectListNodeMemberMapper;

    @Resource
    OAService  oaService;




    @Override
    public List<ProjectListNodeMemberVO> list(ProjectListVO projectListVO) {

        if("1".equals(projectListVO.getUserFlag())){
            LoginUser loginUser = SecurityUtils.getLoginUser();
            projectListVO.setUserId(loginUser.getUserId());
        }


        if(projectListVO.getTemp() != null){
            String whereSql = "";
            if(projectListVO.getTemp() == 2){
                 whereSql = " and lm.status < 10";
            }else if(projectListVO.getTemp() == 3){
                whereSql = " and lm.status < 10 and lm.overdue > 0";
            }else if(projectListVO.getTemp() == 4){
                whereSql = " and lm.status = 10 ";
            }
            projectListVO.setWhereSql(whereSql);
        }
        return projectListNodeMapper.queryTaskListByUserId(projectListVO);

    }

    /**
     * 查询任务附件列表
     * @param projectNodeMemberId
     * @return
     */
    @Override
    public AjaxResult queryTaskFile(Long projectNodeMemberId) {
        List<JSONObject> files = projectListNodeMapper.queryTaskFile(projectNodeMemberId);
        return AjaxResult.success(files);
    }

    @Override
    public void addFileMember(JSONObject param) {
        projectListNodeMapper.addFileMember(param);
    }

    @Override
    public AjaxResult totalTaskForUser(String userFlag) {

        JSONObject obj = new JSONObject();
        if("1".equals(userFlag)){
            LoginUser loginUser = SecurityUtils.getLoginUser();
            obj.put("userId",loginUser.getUserId());
        }

        JSONObject res = projectListNodeMapper.totalTaskForUser(obj);
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult checkTaskStart(JSONObject param) {

        JSONObject res =  projectListNodeMapper.queryProjectListNodeMember(param);
        if(param.getIntValue("status") == 0){
            if(res.getIntValue("status") != 0){
                return AjaxResult.error("状态错误，请刷新数据");
            }
        }else{
            if(res.getIntValue("status") != 2){
                return AjaxResult.error("状态错误，请刷新数据");
            }
        }

        return AjaxResult.success("操作成功!");
    }

    /**
     * 查询文件列表
     * @param projectListVO
     * @return
     */
    @Override
    public List<JSONObject> getMyProjectFile(ProjectListVO projectListVO) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        projectListVO.setUserId(loginUser.getUserId());

        return projectListNodeMapper.getMyProjectFile(projectListVO);
    }

    @Override
    public List<ProjectListNodeMemberVO> exportByProjectId(ProjectListVO projectListVO) {
        return projectListNodeMapper.exportByProjectId(projectListVO);
    }

    /**
     * 查询PLM文件列表
     * @param obj
     * @return
     */
    @Override
    public AjaxResult queryPLMFile(JSONObject obj) {
        try {
            String plmAddr =paramConfig.getPlmAddr();
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("projcetCode", obj.getString("projectNo"));


            log.info("查询PLM请求参数:{}",paramMap);

            // 创建一个信任所有证书的信任管理器
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };

            // 禁用SSL证书验证
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建一个忽略主机名验证的HostnameVerifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

            String res = (String)  PlmSoapUtil.getWebServiceAndSoap(plmAddr,"GetProjcetFile",paramMap,null);
            log.info("返回数据:{}",res);
            JSONObject val = JSONObject.parseObject(res);
            if(val.getIntValue("code")!=200){
                return AjaxResult.error("查询PLM文件错误:"+val.getString("msg"));
            }
            //仅需要输出文件
            List<JSONObject> list = val.getJSONArray("data").stream().map(item->{
                JSONObject fileItem = (JSONObject) item;
                if("输出文件".equals(fileItem.getString("Type"))){
                    return fileItem;
                }else{
                    return null;
                }
            }).collect(Collectors.toList());

            //节点名称过滤
            if(StringUtils.isNotBlank(obj.getString("workName"))){

                list = list.stream().filter(item->item.getString("WorkName").contains(obj.getString("workName"))).collect(Collectors.toList());
            }

            //节点名称过滤
            if(StringUtils.isNotBlank(obj.getString("fileName"))){
                list = list.stream().filter(item->item.getString("FileName").contains(obj.getString("fileName"))).collect(Collectors.toList());
            }


            return AjaxResult.success("查询成功!",list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询PLM文件异常:{}",e.getMessage());
            return AjaxResult.error("查询PLM文件异常:"+e.getMessage());
        }
    }


    /**
     * 查询PLM文件URL
     * @param fileId
     * @return
     */
    @Override
    public AjaxResult queryPLMFileUrl(String fileId) {
        try{
            String plmAddr =paramConfig.getPlmAddr();
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("docId", fileId);
            log.info("查询PLM请求参数:{}",paramMap);

            // 创建一个信任所有证书的信任管理器
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };

            // 禁用SSL证书验证
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // 创建一个忽略主机名验证的HostnameVerifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

            String res = (String)  PlmSoapUtil.getWebServiceAndSoap(plmAddr,"DownloadFile_PM",paramMap,null);
            log.info("返回数据:{}",res);
            JSONObject obj = JSONObject.parseObject(res);
            if(obj.getIntValue("code")==200){
                return AjaxResult.success("操作成功！",obj.getString("data"));
            }else{
                return AjaxResult.error("获取PLM文件路径错误"+obj.getString("msg"));
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error("获取PLM文件路径异常:{}",e.getMessage());
            return AjaxResult.error("获取PLM文件路径异常"+e.getMessage());
        }


    }



    /**
     * 绑定PLM文件
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult bindPLMFile(JSONObject param) {
        List<Map<String,String>> files = param.getJSONArray("files").stream().map(item->{
            Map<String,String> jsonObject = (Map<String,String>) item;
            jsonObject.put("fileId",jsonObject.get("DocId"));
            jsonObject.put("fileName",jsonObject.get("FileName"));
            return jsonObject;
        }).collect(Collectors.toList());

        param.put("files",files);
        //先删除PLM绑定的文件
        projectListNodeMapper.delFilePLM(param);
        projectListNodeMapper.addFileMember(param);
        //关联PLM的 直接状态改成已完成
        ProjectListNodeMember projectListNodeMember = new ProjectListNodeMember();
        projectListNodeMember.setId(param.getLong("projectNodeMemberId"));
        projectListNodeMember.setStatus(TaskStatusEnum.DONE.getStatus());
        projectListNodeMember.setType(20);//绑定plm文件
        projectListNodeMemberMapper.updateById(projectListNodeMember);

        ProjectListVO projectListVO =  projectListNodeMapper.queryProjectInfo(param.getString("projectNodeMemberId"));
        oaService.checkProjectDone(projectListVO);
        return AjaxResult.success("操作成功!");
    }


}
